import json
from apps.pay.order.dao import OrderDao
from decimal import Decimal
from apps.merchant.item.dao import ItemDao
from apps.pay.order.serializers import OrderBaseSerializer

def dismantleOrderByItemHandle(order):
    ''''
    拆单策略：供应链自营的按照商品的维度拆，加盟店的按照商家的维度拆
    '''
    order = OrderDao().findOneByObjId(order.id)
    # print('order----------', order.orderId, json.loads(order.content))
    if order.scene == 'payForFranchisee':
        data = OrderBaseSerializer(order).data
        data['order'] = order.id
        data['orderId'] = order.orderId + '-' + str(order.shop.id)
        OrderDao().create(data)
    else:
        content = json.loads(order.content)
        if content.get('orderItemList') and len(content.get('orderItemList'))>0:
            res_item = {}
            res_shop = {}
            for item in content.get('orderItemList'):
                item_obj = ItemDao().findOneByObjId(item.get('item'))
                if item_obj.shop.types == '0':
                    if res_item.get(item.get('item')):
                        res_item.get(item.get('item')).append(item)
                    else:
                        res_item[item.get('item')] = []
                        res_item[item.get('item')].append(item)
                if item_obj.shop.types == '1':
                    if res_shop.get(item_obj.shop.id):
                        res_shop.get(item_obj.shop.id).append(item)
                    else:
                        res_shop[item_obj.shop.id] = []
                        res_shop[item_obj.shop.id].append(item)

            for key in res_item.keys():
                data = {
                    "order": order.id,
                    "scene": order.scene,
                    "user": order.user.id,
                    "clientname": order.clientname,
                    "sendType": order.sendType,
                    'addrinfo': order.addrinfo,
                    'orderId': order.orderId + '-' + str(key),
                    "remark": order.remark,
                    "orderStatus": order.orderStatus,
                    "payTime": order.payTime,
                    "payway": order.payway,
                }
                # 给子订单关商户
                good = ItemDao().findOneByObjId(key)

                if good:
                    data['shop'] = good.shop.id if good.shop else None
                # 计算销售价和成本价
                sellingPrice = 0
                costPrice = 0
                realPay = 0
                discountParams = []
                for item in res_item.get(key):
                    sellingPrice = sellingPrice + Decimal(item.get('priceModel').get('sellingPrice')) * Decimal(item.get('payCount'))
                    costPrice = costPrice + + Decimal(item.get('priceModel').get('costPrice')) * Decimal(item.get('payCount'))
                    realPay = realPay + Decimal(item.get('priceModel').get('realPay')) * Decimal(item.get('payCount'))
                if content.get('discountParams') and len(content.get('discountParams'))>0:
                    for discount in content.get('discountParams'):
                        _discount = json.loads(json.dumps(discount))
                        _discount['money'] = str(((sellingPrice/order.sellingPrice) * Decimal(_discount.get('money'))).quantize(Decimal('0.00')))
                        discountParams.append(_discount)

                data['sellingPrice'] = sellingPrice
                data['costPrice'] = costPrice
                data['realPay'] = realPay
                data['content'] = json.dumps({'orderItemList': res_item.get(key), 'discountParams': discountParams})
                OrderDao().create(data)

            for key in res_shop.keys():
                data = {
                    "order": order.id,
                    "scene": order.scene,
                    "user": order.user.id,
                    "clientname": order.clientname,
                    "sendType": order.sendType,
                    'addrinfo': order.addrinfo,
                    'orderId': order.orderId + '-' + str(key),
                    "remark": order.remark,
                    "orderStatus": order.orderStatus,
                    "payTime": order.payTime,
                    "payway": order.payway,
                }
                # 给子订单关商户
                data['shop'] = key
                # 计算销售价和成本价
                sellingPrice = 0
                costPrice = 0
                realPay = 0
                discountParams = []
                for item in res_shop.get(key):
                    sellingPrice = sellingPrice + Decimal(item.get('priceModel').get('sellingPrice')) * Decimal(item.get('payCount'))
                    costPrice = costPrice + + Decimal(item.get('priceModel').get('costPrice')) * Decimal(item.get('payCount'))
                    realPay = realPay + Decimal(item.get('priceModel').get('realPay')) * Decimal(item.get('payCount'))
                if content.get('discountParams') and len(content.get('discountParams'))>0:
                    for discount in content.get('discountParams'):
                        _discount = json.loads(json.dumps(discount))
                        _discount['money'] = str(((sellingPrice/order.sellingPrice) * Decimal(_discount.get('money'))).quantize(Decimal('0.00')))
                        discountParams.append(_discount)

                data['sellingPrice'] = sellingPrice
                data['costPrice'] = costPrice
                data['realPay'] = realPay
                data['content'] = json.dumps({'orderItemList': res_shop.get(key), 'discountParams': discountParams})
                OrderDao().create(data)